package scraper

import (
	"context"

	"database/sql"

	"github.com/prometheus/client_golang/prometheus"
	"go.uber.org/zap"
)

var memorySQL = `SELECT SUM(TOTAL_SIZE) FROM V$MEM_POOL;`

var scrapeMemoryDesc = prometheus.NewDesc(
	prometheus.BuildFQName(Namespace, Exporter, "collect_memory_MB"),
	"Collector Memory.",
	[]string{"collector"},
	nil,
)

type ScrapeMemory struct{}

func (ScrapeMemory) Name() string {
	return "memory"
}

func (ScrapeMemory) Usage() string {
	return "Total memory used by kingbaseDB"
}

func (ScrapeMemory) Scraper(ctx context.Context, db *sql.DB, ch chan<- prometheus.Metric, logger *zap.Logger) error {
	t := 0
	err := db.QueryRow(memorySQL).Scan(&t)
	if err != nil {
		logger.Sugar().Errorf("Failed to scrape memory: %v", err.Error())
		return err
	}
	ch <- prometheus.MustNewConstMetric(
		scrapeMemoryDesc, prometheus.GaugeValue, float64(t>>20), "connection",
	)
	return nil
}

var _ DBScraper = (*ScrapeMemory)(nil)
